package com.cqndt.disaster.device.service.data.impl;

import com.cqndt.disaster.device.dao.data.TabAreaMapper;
import com.cqndt.disaster.device.entity.data.TabArea;
import com.cqndt.disaster.device.service.data.TabAreaService;
import com.cqndt.disaster.device.sys.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TabAreaServiceImpl implements TabAreaService {

    @Autowired
    private TabAreaMapper tabAreaMapper;

    @Override
    public List<TabArea> TabAreaList(SysUserVo sysUserVo) {
        List<TabArea> tabAreas = tabAreaMapper.TabAreaList();
//       sysUserVo.getAreaCode();
        List<TabArea> tabAreaList = getArea(Integer.parseInt(sysUserVo.getAreaCode()), tabAreas, null);
        TabArea tabArea = tabAreaMapper.selectByPrimaryKey(Integer.parseInt(sysUserVo.getAreaCode()));
        tabAreaList.add(tabArea);
        return tabAreaList;
    }

    private  List<TabArea> getArea(Integer areaCode, List<TabArea> listArea, Integer level){
        List<TabArea> tempArea = new ArrayList<>();
        for(TabArea area : listArea){
            // 判断条件是否带入等级
            boolean isParent = false;

            if(level == null){
                isParent = areaCode.equals(area.getAreaParent());
            } else {
                isParent = (areaCode.equals(area.getAreaParent()) && Integer.parseInt(area.getLevel()) == (level+1));
            }

            if(isParent){
                // 表示当前地区为上一地区的子集，存入集合中
                tempArea.add(area);
                // 地区编号可能为空
                if(area.getAreaCode() != null){
                    List<TabArea> childAreas = getArea(area.getAreaCode(), listArea, Integer.parseInt(area.getLevel()));
                    if(!childAreas.isEmpty()){
                        tempArea.addAll(childAreas);
                    }
                }
            }
        }
        return tempArea;
    }
}
